package com.yuhanginfo.modules.sys.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.service.CrudService;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.modules.sys.entity.Area;
import com.yuhanginfo.modules.sys.entity.Car;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.GoodsMateriel;
import com.yuhanginfo.modules.sys.entity.Store;
import com.yuhanginfo.modules.sys.entity.StoreArea;
import com.yuhanginfo.modules.sys.entity.StoreGoods;
import com.yuhanginfo.modules.sys.entity.SysShoppingCart;
import com.yuhanginfo.modules.sys.entity.User;
import com.yuhanginfo.modules.sys.utils.CodeUtil;
import com.yuhanginfo.modules.sys.utils.UserUtils;
import com.yuhanginfo.modules.sys.dao.AreaDao;
import com.yuhanginfo.modules.sys.dao.CarDao;
import com.yuhanginfo.modules.sys.dao.GoodsDao;
import com.yuhanginfo.modules.sys.dao.GoodsMaterielDao;
import com.yuhanginfo.modules.sys.dao.StoreDao;
import com.yuhanginfo.modules.sys.dao.StoreGoodsDao;
import com.yuhanginfo.modules.sys.dao.SysShoppingCartDao;

/**
 * 平台商品信息管理Service
 * 
 * @author yinhao
 * @version 2017-09-11
 */
@Service
@Transactional(readOnly = true)
public class GoodsService extends CrudService<GoodsDao, Goods> {
	@Autowired
	GoodsMaterielDao goodsMaterielDao;
	@Autowired
	private GoodsDao goodsDao;
	
	@Autowired 
	private AreaDao areaDao;
	
	@Autowired 
	private StoreDao storeDao;
	
	@Autowired 
	private StoreGoodsDao storeGoodsDao;
	
	@Autowired
	private CarDao carDao;
	
	@Autowired
	private SysShoppingCartDao shoppingCartDao;
	


	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void save(String userId, Goods goods, String image, String detail, String service,String[] imageSelect,String[] detailSelect,String[] serviceSelect) {
			//存在则假删除
			if(goods.getId() != null && !"".equals(goods.getId())){
				super.delete(goods);
				GoodsMateriel delGoodsMateriel = new GoodsMateriel();
				delGoodsMateriel.setGoodsCode(goods.getCode());
				goodsMaterielDao.delete(delGoodsMateriel);
			}
			String goodsCode = CodeUtil.getGoodsCode();
			goods.setImage(this.sortImg(this.formatImg(goods.getDeleteImage(),goods.getImage(),image), imageSelect));
			goods.setDetail(this.sortImg(this.formatImg(goods.getDeleteDetail(),goods.getDetail(),detail),detailSelect));
			goods.setService(this.sortImg(this.formatImg(goods.getDeleteService(),goods.getService(),service),serviceSelect));
			goods.setCode(goodsCode);
			goods.setStatus(0);
			goods.setSource("2");
			goods.setIsNewRecord(true);
			super.save(goods);
			GoodsMateriel goodsMateriel = new GoodsMateriel();
			goodsMateriel.setGoodsCode(goods.getCode());
			goodsMateriel.setMaterielCode(goods.getMaterielCode());
			goodsMateriel.setCreateDate(goods.getCreateDate());
			goodsMateriel.setCreateBy(goods.getCreateBy());
			goodsMateriel.setUpdateDate(goods.getUpdateDate());
			goodsMateriel.setUpdateBy(goods.getUpdateBy());
			goodsMateriel.setIsNewRecord(true);
			goodsMaterielDao.insert(goodsMateriel);
		
	}

	@Transactional(readOnly = false)
	public void delete(Goods goods) {
		super.delete(goods);
	}

	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void up(Goods goods,String storeId){
		String[] stroreArray = storeId.split(",");
		User user = UserUtils.getUser();
		Date nowDate = new Date();
		//如果没有选择任何门店并且是上架状态,则做下架处理
		if(stroreArray.length == 1 && "".endsWith(stroreArray[0])){
			if(goods.getStatus() == 1){
				Goods queryGoods = new Goods();
				queryGoods.setId(goods.getId());
				queryGoods.setStatus(2);
				queryGoods.setUpdateDate(nowDate);
				queryGoods.setUpdateBy(user);
				goodsDao.update(queryGoods);
				//将上架变为历史
				StoreGoods queryStoreGoods = new StoreGoods();
				queryStoreGoods.setGoodsCode(goods.getCode());
				queryStoreGoods.setIsHistorySell(1);
				storeGoodsDao.updateByGoodsCode(queryStoreGoods);
			}
		}else{
				Goods queryGoods = new Goods();
				queryGoods.setId(goods.getId());
				queryGoods.setStatus(1);
				queryGoods.setUpdateDate(nowDate);
				queryGoods.setUpdateBy(user);
				queryGoods.setUpDate(nowDate);
				goodsDao.update(queryGoods);
				//将上架变为历史
				StoreGoods queryStoreGoods = new StoreGoods();
				queryStoreGoods.setGoodsCode(goods.getCode());
				queryStoreGoods.setIsHistorySell(1);
				storeGoodsDao.updateByGoodsCode(queryStoreGoods);
				//对购物城中所有该商品进行失效处理
				SysShoppingCart shoppingCart = new SysShoppingCart();
				shoppingCart.setGoodsCode(goods.getCode());
				shoppingCart.setStatus("0");
				shoppingCartDao.changeStatus(shoppingCart);
				//生成本次上架
				List<StoreGoods> list = new ArrayList<>();
				for(int i=0;i<stroreArray.length;i++){
					StoreGoods s = new StoreGoods();
					Store store = storeDao.get(stroreArray[i]);
					s.setStoreCode(store.getCode());
					s.setGoodsCode(goods.getCode());
					s.setStock(1);
					s.setIsHistorySell(0);
					s.setIsHisttoryStocks(0);
					s.setSellNum(null);
					s.setCreateBy(user);
					s.setCreateDate(nowDate);
					s.setUpdateBy(user);
					s.setUpdateDate(nowDate);
					s.setDelFlag("0");
					list.add(s);
					//对购物车进行操作
					shoppingCart.setGoodsCode(goods.getCode());
					shoppingCart.setStoreCode(store.getCode());
					shoppingCart.setStatus("1");
					shoppingCartDao.changeStatus(shoppingCart);
				}
				storeGoodsDao.batchInsert(list);
		}
			
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchUp(String goodsId,String storeId){
		String[] goodsArray = goodsId.split(",");
		String[] stroreArray = storeId.split(",");
		User user = UserUtils.getUser();
		Date nowDate = new Date();
		if(goodsArray.length == 1 && "".endsWith(goodsArray[0])){
			return;
		}
		if(stroreArray.length == 1 && "".endsWith(stroreArray[0])){
			return;
		}
		for(int i=0;i<goodsArray.length;i++){
			Goods goods = goodsDao.get(goodsArray[i]);
			//非上架状态才执行
			if(goods.getStatus() != 1){
				Goods queryGoods = new Goods();
				queryGoods.setId(goods.getId());
				queryGoods.setStatus(1);
				queryGoods.setUpdateDate(nowDate);
				queryGoods.setUpdateBy(user);
				queryGoods.setUpDate(nowDate);
				goodsDao.update(queryGoods);
				//将上架变为历史
				StoreGoods queryStoreGoods = new StoreGoods();
				queryStoreGoods.setGoodsCode(goods.getCode());
				queryStoreGoods.setIsHistorySell(1);
				storeGoodsDao.updateByGoodsCode(queryStoreGoods);
				//对购物城中所有该商品进行失效处理
				SysShoppingCart shoppingCart = new SysShoppingCart();
				shoppingCart.setGoodsCode(goods.getCode());
				shoppingCart.setStatus("0");
				shoppingCartDao.changeStatus(shoppingCart);
				//生成本次上架
				List<StoreGoods> list = new ArrayList<>();
				for(int y=0;y<stroreArray.length;y++){
					StoreGoods s = new StoreGoods();
					Store store = storeDao.get(stroreArray[y]);
					s.setStoreCode(store.getCode());
					s.setGoodsCode(goods.getCode());
					s.setStock(1);
					s.setIsHistorySell(0);
					s.setIsHisttoryStocks(0);
					s.setSellNum(null);
					s.setCreateBy(user);
					s.setCreateDate(nowDate);
					s.setUpdateBy(user);
					s.setUpdateDate(nowDate);
					s.setDelFlag("0");
					list.add(s);
					//对购物车进行操作
					shoppingCart.setGoodsCode(goods.getCode());
					shoppingCart.setStoreCode(store.getCode());
					shoppingCart.setStatus("1");
					shoppingCartDao.changeStatus(shoppingCart);
				}
				storeGoodsDao.batchInsert(list);
			}
		}
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void down(Goods goods){
		if(goods.getStatus() == 1){
			Goods queryGoods = new Goods();
			queryGoods.setId(goods.getId());
			queryGoods.setStatus(2);
			queryGoods.setUpdateDate(new Date());
			queryGoods.setUpdateBy(UserUtils.getUser());
			goodsDao.update(queryGoods);
			//将上架变为历史
			StoreGoods queryStoreGoods = new StoreGoods();
			queryStoreGoods.setGoodsCode(goods.getCode());
			queryStoreGoods.setIsHistorySell(1);
			storeGoodsDao.updateByGoodsCode(queryStoreGoods);
		}
	}

	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchDown(String[] arrayId){
		for(int i=0;i<arrayId.length;i++){
			Goods goods = goodsDao.get(arrayId[i]);
			if(goods.getStatus() == 1){
				Goods queryGoods = new Goods();
				queryGoods.setId(goods.getId());
				queryGoods.setStatus(2);
				queryGoods.setUpdateDate(new Date());
				queryGoods.setUpdateBy(UserUtils.getUser());
				goodsDao.update(queryGoods);
				//将上架变为历史
				StoreGoods queryStoreGoods = new StoreGoods();
				queryStoreGoods.setGoodsCode(goods.getCode());
				queryStoreGoods.setIsHistorySell(1);
				storeGoodsDao.updateByGoodsCode(queryStoreGoods);
			}
		}
	}
	
	
	@Transactional(readOnly = true)
	public Map<String,Object> getStoreGoods(Goods goods){
		Map<String,Object> resultMap = new HashMap<>();
		List<Area> areaList=areaDao.areaStoreList();
		List<StoreArea> saList=new ArrayList<>();
		for(Area a:areaList) {
			StoreArea sa=new StoreArea();
			sa.setId(a.getId());
			sa.setArea(a.getName());
			sa.setStoreList(storeDao.findStoreByClassify(a.getId()));
			saList.add(sa);
		}
		List<Store> checkStoreList = storeDao.selectWithStoreGoodsByGoodsCode(goods.getCode());
		resultMap.put("checkStoreList", checkStoreList);
		resultMap.put("allChecks", saList);
		resultMap.put("resultCode", 1);
		return resultMap;
	}


	public List<Goods> selectByStoreCode(String id) {
			
		return goodsDao.selectByStoreCode(id);
	}

	public List<Goods> selectByStoreCodes(String id) {
		
		return goodsDao.selectByStoreCodes(id);
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Map<String,Object> del(Goods goods) {
		Map<String,Object> resultMap = new HashMap<>();
		if(goods.getStatus() == 1){
			resultMap.put("resultCode", 0);
			resultMap.put("resultMessage", "该商品为上架状态，不可删除！");
			return resultMap;
		}
		super.delete(goods);
		//删除商品门店关系
		StoreGoods storeGoods = new StoreGoods();
		storeGoods.setGoodsCode(goods.getCode());
		storeGoods.setUpdateDate(goods.getUpdateDate());
		storeGoods.setUpdateBy(goods.getUpdateBy());
		storeGoodsDao.delete(storeGoods);
		return resultMap;
}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchDel(String[] arrayId) {
			for(int i=0;i<arrayId.length;i++){
				Goods queryGoods = new Goods();
				queryGoods.setId(arrayId[i]);
				Goods resultGoods = goodsDao.get(queryGoods);
				if(resultGoods.getStatus() != 1){
					super.delete(queryGoods);
					StoreGoods storeGoods = new StoreGoods();
					storeGoods.setGoodsCode(resultGoods.getCode());
					storeGoods.setUpdateDate(new Date());
					storeGoods.setUpdateBy(UserUtils.getUser());
					storeGoodsDao.delete(storeGoods);
				}
			}
	}

	public Page<Goods> selectPageGoodsByMateriel(Page<Goods> page,Goods goods ) {
		goods.setPage(page);
		page.setList(goodsDao.selectPageGoodsByMateriel(goods));
		return page;
	}

	public List<Goods> selectGoodsByIds(String[] checkedGoods) {
		return goodsDao.selectGoodsByIds(checkedGoods);
	}

	public List<Goods> replaceOrder(Goods goods1) {
		
		return goodsDao.replaceOrder(goods1);
	}
	
	//对比文件名，将未删除的文件和新上传的文件组合保留
	private String formatImg(String delImg,String oldImg,String newImg){
		String finalImg = "";
		boolean delFlagFlag = false;
		if( null!=delImg && !"".equals(delImg) && null!=oldImg && !"".equals(oldImg)){
			String[]  delImgArray = delImg.split(";");
			String[]  oldImgArray = oldImg.split(";");
			for(int i=0;i<oldImgArray.length;i++){
				boolean delFlag = true;
				for(int y=0;y<delImgArray.length;y++){
					
					if(oldImgArray[i].substring(oldImgArray[i].lastIndexOf('/')+1, oldImgArray[i].lastIndexOf('.')).equals(delImgArray[y])){
						delFlag = false;
						break;
					}
				}
				if(delFlag){
					if(delFlagFlag){
						finalImg += ";";
					}
					if(!delFlagFlag){
						delFlagFlag = true;
					}
					finalImg += oldImgArray[i];
				}
			}
		}else if( null!=oldImg && !"".equals(oldImg)){
			finalImg += oldImg;
		}
		if( null!=newImg && !"".equals(newImg)){
			if(finalImg != null && !"".equals(finalImg)){
				finalImg += ";";
			}
			finalImg += newImg;
		}
		return finalImg;
	}
	
	//排序
	private String sortImg(String img,String[] sort){
		if(sort == null){
			return img;
		}
		StringBuilder finalImg = new StringBuilder();
		String[] imgList = img.split(";");
	
		for(int i=0;i<sort.length;i++){
			if(i>0){
				finalImg.append(";");
			}
			finalImg.append(imgList[Integer.valueOf(sort[i])-1]);
		}
		return finalImg.toString();
	}
	
	public Goods getGoodsByCode(Map<String,String> params) {
		Goods goods=goodsDao.getGoodsByCode(params);
		String partCode=goods.getPartCode();
		List<String> carInfo=getCarInfoByPartNo(partCode);
		goods.setCarList(carInfo);
		return goods;
	}
	
	public List<String> getCarInfoByPartNo(String partNo) {
		List<String> resultList = new ArrayList<>();
		List<Car> carList = carDao.getCarInfoByPartNo(partNo);
		for (Car car : carList) {
			String carBarand=StringUtils.isNotEmpty(car.getCarBarand())?car.getCarBarand():"";
			String carCode=StringUtils.isNotEmpty(car.getCarCode())?car.getCarCode():"";
			String carYear=StringUtils.isNotEmpty(car.getCarYear())?car.getCarYear():"";
			String carInfo = carBarand + "/" + carCode + "/" + carYear;
			resultList.add(carInfo);
		}
		return resultList;
	}
}